<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>服务管理</el-breadcrumb-item>
      <el-breadcrumb-item>装修服务</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card>
      <!-- 搜索查询 -->
      <el-row :gutter="20">
        <el-col :span="6">
          <div>
            <el-input v-model="queryParam.name" placeholder="请输入服务名称" class="input-with-select" clearable></el-input>
          </div>
        </el-col>
        <el-col :span="6">
          <el-button type="primary" @click="handleSizeChange(10)">查询</el-button>
          <el-button type="primary" @click="serviceFormVisible = true">添加服务</el-button>
        </el-col>
      </el-row>
      <!-- table表格数据 start -->
      <template>
        <el-table :data="serviceDataList" style="width: 100%" max-height="570">
          <!-- 数据表 -->
          <el-table-column fixed prop="name" label="名称" width="150">
          </el-table-column>
          <el-table-column prop="image" label="图片" width="120">
            <template slot-scope="scope">
              <div v-if="scope.row.image_arr[0]" class="demo-image__preview">
                <el-image style="width: 100px; height: 100px" :src="scope.row.image_arr[0].url" :preview-src-list="[scope.row.image_arr[0].url]">
                </el-image>
              </div>
              <div v-else>暂无图片</div>
            </template>
          </el-table-column>
          <el-table-column prop="describe" label="描述" width="400">
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="140">
            <!-- 操作 -->
            <template slot-scope="scope">
              <!-- <el-button size="mini" type="warning" icon="el-icon-view" circle></el-button> -->
              <el-button size="mini" type="warning" icon="el-icon-edit" @click="editService(scope.row)" circle></el-button>
              <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteService(scope.$index, scope.row.id)"
                circle></el-button>
            </template>
          </el-table-column>
        </el-table>
      </template>
      <!-- table表格数据 end -->
      <!-- 分页  start-->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="queryParam.currentPage"
        :page-sizes="[10, 20, 30, 40]" :page-size="100" layout="total, sizes, prev, pager, next, jumper" :total="totalResult">
      </el-pagination>
      <!-- 分页  end> -->
    </el-card>
    <!-- 表单 start -->
    <el-dialog title="提示" :visible.sync="serviceFormVisible" width="40%" @close="closeServiceForm" center>
      <el-form :model="serviceForm" :rules="serviceFormRules" ref="serviceFormRef" label-width="100px" class="demo-ruleForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="serviceForm.name"></el-input>
        </el-form-item>
        <el-form-item label="服务描述简介" prop="describe">
          <el-input type="textarea" v-model="serviceForm.describe"></el-input>
        </el-form-item>
        <el-form-item label="图片" prop="image">
          <template>
            <!-- 图片上传 -->
            <el-upload class="upload-demo" accept="image/*" :data="uploadParams.uploadData" :action="uploadParams.uploadFileUrl"
              :headers="uploadParams.uploadHeaders" list-type="picture" :on-success="uploadSuccess" :file-list='serviceForm.image_arr'
              :on-preview="uploadPreview" :on-remove="uploadRemove" :limit="1" :on-exceed="handleExceed">
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
            </el-upload>
          </template>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="resetServiceForm">重置</el-button>
        <el-button type="primary" @click="updateOrCreateServiceForm">确认</el-button>
      </span>
    </el-dialog>
    <!-- 表单 end -->
    <!-- 图片预览 -->
    <el-dialog title="图片预览" :visible.sync="imagePreviewVisible" width="30%">
      <div class="demo-image">
        <div class="block">
          <el-image style="width: 100%; height: 100%" :src="previewPath" fit="fill"></el-image>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import {
    _getAdornServiceListApi,
    _updateOrCreateAdornServiceApi,
    _deleteAdornServiceApi,
    getUploadParamsApi
  } from '../request/api.js'
  export default {
    data() {
      return {
        serviceDataList: [],
        totalResult: 0,
        queryParam: {
          name: '',
          currentPage: 1,
          pageSize: 10
        },
        operate: 'add',
        serviceForm: {},
        serviceFormTemp: {
          describe: '',
          image: null,
          name: '',
          image_arr: []
        },
        serviceFormVisible: false,
        serviceFormRules: {
          name: [{
            required: true,
            message: '请输入名称',
            trigger: 'blur'
          }],
          image: [{
            required: true,
            message: '请选择图片',
            trigger: 'blur'
          }]
        },
        // 文件上传
        // 预览图片地址
        previewPath: '',
        imagePreviewVisible: false
      }
    },
    created() {
      this.serviceForm = JSON.parse(JSON.stringify(this.serviceFormTemp))
      this.getServiceList()
      // 获取文件上传的参数配置
      this.uploadParams = getUploadParamsApi('adorn_service')
    },
    methods: {
      // 获取列表数据
      async getServiceList() {
        // 获取服务列表
        const {
          data: res
        } = await _getAdornServiceListApi({
          params: this.queryParam
        })
        console.log(res)
        this.serviceDataList = res.data.dataList
        this.totalResult = res.data.totalResult
      },
      // 分页事件
      handleSizeChange(newSize) {
        this.queryParam.pageSize = newSize
        this.queryParam.currentPage = 1
        this.getServiceList()
      },
      handleCurrentChange(newPage) {
        this.queryParam.currentPage = newPage
        this.getServiceList()
      },
      updateOrCreateServiceForm() {
        this.$refs.serviceFormRef.validate(async valid => {
          if (valid) {
            const res = await _updateOrCreateAdornServiceApi(this.serviceForm, this.operate)
            console.log(res)
            if (res.data.status) {
              var message = this.operate === 'add' ? '添加成功！' : '编辑成功！'
              this.$message.success(message)
              this.serviceFormVisible = false
              this.operate = 'add'
              this.getServiceList()
            } else {
              this.$message.error('操作失败！')
            }
          }
        })
      },
      // 编辑
      editService(service) {
        this.serviceForm = service
        this.operate = 'edit'
        this.serviceFormVisible = true
      },
      // 删除
      deleteService(index, id) {
        this.$confirm('确认删除？').then(async _ => {
          const data = await _deleteAdornServiceApi(id)
          if (data.status === 200 && data.data.status) {
            this.$message.success('删除成功！')
            this.serviceDataList.splice(index, 1)
          }
        }).catch(_ => {})
      },
      // 重置表单
      resetServiceForm() {
        this.serviceForm = JSON.parse(JSON.stringify(this.serviceFormTemp))
        this.$refs.serviceFormRef.resetFields()
      },
      // 关闭表单
      closeServiceForm() {
        this.resetServiceForm()
        this.serviceFormVisible = false
      },
      // 文件上传成功回调
      uploadSuccess(response) {
        if (response.status) {
          this.serviceForm.image = response.data.id
        }
      },
      // 移除文件
      uploadRemove(file) {
        this.serviceForm.image = null
      },
      // 预览图片
      uploadPreview(file) {
        this.imagePreviewVisible = true
        this.previewPath = file.url
      },
      // 文件超出个数限制时的钩子
      handleExceed(files, fileList) {
        this.$message.warning('只允许上传一图片，请删除后重新上传')
      }
    }
  }
</script>

<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    margin: 25px;
  }

  .avatar {
    width: 80px;
    height: 80px;
    display: block;
  }
</style>
